package ipebg.mzk.provider.system.service.impl;

import ipebg.mzk.common.util.Page;
import ipebg.mzk.facade.entity.MsAdminUser;
import ipebg.mzk.facade.entity.Org;
import ipebg.mzk.facade.system.bean.AdminUserBean;
import ipebg.mzk.facade.system.service.OrgService;
import ipebg.mzk.facade.system.service.PagerService;
import ipebg.mzk.facade.system.service.UserService;
import ipebg.mzk.provider.system.dao.UserDao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("userServiceImpl")
//@CacheConfig(cacheNames ={"cacheUserService"})
public class UserServiceImpl implements UserService {

	private static final Log log = LogFactory.getLog(UserServiceImpl.class);
	
	@SuppressWarnings("rawtypes")
	@Resource(name = "pageServiceImpl")
	private PagerService pageServiceImpl;
	
	@Resource(name = "orgServiceImpl")
	private OrgService orgService;
	
	@Resource(name = "userDao")
	private UserDao userDao;
	
	
	
	@Override
	@Cacheable(value="mzk.UserServiceImpl.getAllList",key="'getAllList.key_'+#user.getLoginName()+#from+#length",condition="#user!=null")
	@Transactional(readOnly=true)
	public Page getAllList(MsAdminUser user, int from, int length) throws Exception {
		Page materialCodeList;
		String hql = "from MsAdminUser u where u.adminId is not null";
		if(user != null){
			if(user.getLoginName() != null && !user.getLoginName().equals("")){
				hql += " and u.loginName like '%" + user.getLoginName() + "%'";
			}
			if(user.getRealName() != null && !user.getRealName().equals("")){
				hql += " and u.realName like '%" + user.getRealName() + "%'";
			}
		}
		hql +=" order by u.createdTime desc ";
		log.info("query For User List:"+hql);
		try {
			materialCodeList = pageServiceImpl.findPageByhqlQuery(from, length, hql);
		} catch (Exception e) {
			throw e;
		}		
		return materialCodeList;
	}

	@Override
	@Transactional(readOnly=true)
	public List<AdminUserBean> toBean(List<MsAdminUser> userList) throws Exception {
		List<AdminUserBean> beanList = new ArrayList<AdminUserBean>();
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
			for(MsAdminUser u : userList){
				AdminUserBean bean = new AdminUserBean();

				bean.setUserId(u.getAdminId());
				bean.setLoginName(u.getLoginName());
				bean.setPassword(u.getPassword());
				bean.setRealName(u.getRealName());
				bean.setPhone(u.getPhone());
				bean.setTelePhone(u.getTelePhone());
				bean.setEmail(u.getEmail());
				bean.setDominate(u.getDominate());
				bean.setOrgId(u.getOrgId());
				
				Org org = orgService.findById(u.getOrgId()==null?"":u.getOrgId());
				
				if(org == null || org.equals(null)){
					bean.setOrgName("");
				}else{
					bean.setOrgName(org.getOrgName());
				}
				
				bean.setEnabled(u.getEnabled());
				bean.setDescription(u.getDescription());
				
				String createdTime = null;
				if(u.getCreatedTime() == null){
					createdTime = null;
				}else{
					createdTime = date.format(u.getCreatedTime());
				}			
				bean.setCreatedTime(createdTime);
				
				String modifyTime = null;
				if(u.getEditTime() == null){
					modifyTime = null;
				}else{
					modifyTime = date.format(u.getEditTime());
				}
				bean.setEditTime(modifyTime);
				
				beanList.add(bean);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		return beanList;
	}

	
	@Override
	@Transactional(readOnly=true)
	@CacheEvict(value={"mzk.UserServiceImpl.getAllList","mzk.UserServiceImpl.findUserById"
			,"mzk.UserServiceImpl.findUserByEmpNo"},allEntries = true)
	public void saveOrUpdate(MsAdminUser user) {
		try {
			userDao.saveOrUpdate(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	@CacheEvict(allEntries = true)
	public boolean delete(String userId) throws Exception {
		boolean flag = false;
		try {
			MsAdminUser user = userDao.findById(userId);
			user.setEnabled("2");
			userDao.saveOrUpdate(user);
			//狀態改為無效 ，并不刪除
			/*userDao.delete(user);*/

			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return flag;
	}

	
/*	 @Cacheable(value = "orderServiceImpl.selectInterests",key = "'selectInterests_'+#params.get('user_id')+'_'+#params.get('type')+'_'+#pager.pageNumber")//增加redis缓存
	    @Override
	    public Pager<Interest> selectInterests(Map<String, Object> params, Pager<Interest> pager) {
	        System.out.println("select selectInterests class ....");
	        pager.setList(interestMapper.findInterestListV3(params, pager));
	        pager.setTotalCount(interestMapper.findCountInterestListV3(params));
	        return pager;
	    }*/
	
	@Override
	@Transactional(readOnly = true)
<<<<<<< HEAD
    @Cacheable(value="mzk.UserServiceImpl.findUserById", key = "'findUserById.key_'+#userId")
=======
    @Cacheable(value="mzk.UserServiceImpl.findUserById", key = "findUserById.key_'+#userId")
>>>>>>> ce8566db0175a5dea3ad94289e2ccc7ffd8a63f3
	public MsAdminUser findUserById(String userId) {
		return userDao.findById(userId);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly=true)
	@Cacheable(value="mzk.UserServiceImpl.findUserByEmpNo",key = "'findUserByEmpNo.key_'+#no")
	public MsAdminUser findUserByEmpNo(String no) {
		List<MsAdminUser> userList = userDao.findByProperty(MsAdminUser.class,new String[]{"loginName"},new Object[]{no});
		if(userList.size() > 0)
			return userList.get(0);
		else
			return null;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly=true)
	public MsAdminUser getEnableUserByName(String userName) {
		List<MsAdminUser> result = null;
		try {
			String hql = "from MsAdminUser u where u.loginName='" + userName.trim()	+ "' and u.enabled='1'";
			result=userDao.queryForList(hql, null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//session.close();
		}
		if(result!=null&&result.size()>0){
			return result.get(0);
		}else{
			return null;
		}
	}
	
	@Transactional(readOnly=true)
	@SuppressWarnings("unchecked")
	public String getMail(String empNo) {
		try {
			List<MsAdminUser> userList = userDao.findByProperty(MsAdminUser.class,new String[]{"loginName"},new Object[]{empNo});
			if (userList.size() > 0) {
				log.info("工號為"+empNo+"的員工郵箱獲取成功！");
				return userList.get(0).getEmail();
			} else {
				return "Email is null";
			}
		} catch (Exception e) {
			log.error("工號為"+empNo+"的員工郵箱獲取異常！",e);
			log.error(e.getMessage(),e);
			return "failed when getMail";
		}

	}

	@Override
	@Transactional(readOnly=true)
	@Cacheable
	public List<MsAdminUser> findAllUser() throws Exception {
		List<MsAdminUser> userList=null;
		try {
			userList = userDao.findAll(new String[]{"loginName"});
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			throw e;
		}
		return userList;
	}
}
